'use strict'

const { exec } = require('child_process')
import path from 'path'
import { app, protocol, BrowserWindow, Menu, dialog } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import WinState from 'electron-win-state'
import electronInit from './electron-service/' // 主进程直接调用
const winState = new WinState({
  defaultWidth: 1000,
  defaultHeight: 800,
})

// 通过检查第二个实例启动时的事件来避免多个实例运行
const gotTheLock = app.requestSingleInstanceLock()
// Scheme must be registered before the app is ready
protocol.registerSchemesAsPrivileged([{ scheme: 'app', privileges: { secure: true, standard: true } }])

let win
let printLiving

async function createWindow() {
  const config = {
    ...winState.winOptions,
    minWidth: 400, // 设置最小宽度
    webPreferences: {
      contextIsolation: false,
      enableRemoteModule: true,
      nodeIntegration: true,
      webSecurity: false, //允许跨域访问本地图片
      webviewTag: true,
    },
  }
  Menu.setApplicationMenu(null) // null值取消顶部菜单栏

  win = new BrowserWindow(config)
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the index.html when not in development
    win.loadURL('app://./index.html')
  }
  winState.manage(win)
}

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  // 当所有的窗口都被关闭时触发。
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  // 当应用被激活时发出
  // 各种操作都可以触发此事件, 例如首次启动应用程序、尝试在应用程序已运行时或单击应用程序的坞站或任务栏图标时重新激活它。
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

app.on('ready', async () => {
  if (!gotTheLock) {
    app.quit()
  } else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
      if (win) {
        if (win.isMinimized()) {
          win.restore()
        }
        win.focus()
      }
    })
    createWindow()
    electronApiInit()

    win.on('closed', () => {
      win = null
    })
  }
  // win.on('close', () => {
  //   checkAndKillProcess('打印组件.exe')
  // })
})

// 主进程注册事件
function electronApiInit() {
  try {
    process.env.WEBPACK_DEV_SERVER_URL && win.setIcon(path.join(__dirname, `../public/favicon.png`))
    printLiving = new electronInit.Print(win)
    // electronInit.TrayInit(win)
    // electronInit.ipcInit(win)
    electronInit.initPrintList(win, printLiving)
    electronInit.socket.createServer(printLiving)
    electronInit.electronUpdate(win)
  } catch (error) {
    dialog.showErrorBox('ElectronApiInit', JSON.stringify(error.message))
  }
}

function checkAndKillProcess(processNameOrID) {
  exec('tasklist', (error, stdout, stderr) => {
    if (error) {
      return
    }

    if (stdout.includes(processNameOrID)) {
      exec(`taskkill /F /IM ${processNameOrID}`, (error, stdout, stderr) => {
        if (error) {
          console.error(`关闭进程失败: ${error.message}`)
        } else {
          console.log(`进程已成功关闭: ${stdout}`)
        }
      })
    }
  })
}
